/**
 * fileName: JsonResult.java
 *     Date: 2012-4-30
 **/
package com.stranger.common.core;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;


import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.StrutsResultSupport;


import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.util.ValueStack;

/**
 * @作者 stranger.lin
 *
 * @时间 2012-4-30
 */
public class JsonResult extends StrutsResultSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = -1119324025766990105L;

	private static final String DEFAULT_CONTENT_TYPE="application/json";
	
	private static final String DEFAULT_ENCODING="UTF-8";
	
	private String root;
	private String contentType;

	@Override
	public void execute(ActionInvocation invocation) throws Exception {
		super.execute(invocation);
		try {
			/**获得action上下文*/
			//HttpServletRequest request=ServletActionContext.getRequest();
			HttpServletResponse response=ServletActionContext.getResponse();
			response.setCharacterEncoding(DEFAULT_ENCODING);
			response.setContentType(contentType);
			PrintWriter writer= response.getWriter();
			 Map<String,Object> rootMap=new HashMap<String, Object>();
			 ValueStack stack= invocation.getStack();
			if (root!=null) {
				
				   
				   if (this.root.indexOf(",")!=-1) {
					String[] roots=this.root.split(",");
					for (String keyRoot : roots) {
						rootMap.put(keyRoot, stack.findValue(keyRoot));
					}
					
				}else {
					rootMap.put(this.root,stack.findValue(this.root));
				}
				   System.err.println(stack.size()+"----");
			}
			//writer.print(JSONUtil.serialize(rootMap)) ;
			//JSONUtil.serialize(writer, rootMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@Override
	protected void doExecute(String arg0, ActionInvocation invocation) {
		
		
		
	}

	public String getRoot() {
		return root;
	}

	public void setRoot(String root) {
		this.root = root;
	}

	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}
	
	

}
